const g = require('../utils/global');
const { randEnemySpeed } = require('../utils/helper');

cc.Class({
    extends: cc.Component,

    properties: {
        plane: {
            type: cc.Sprite,
            default: null,
        },
        // 所有敌机类型
        enemyList: {
            type: [cc.SpriteFrame],
            default: [],
        },
    },

    // LIFE-CYCLE CALLBACKS:

    // 初始化
    initWithModel(model) {
        this.model = model;
        this.node.x = this.checkPosX(model.startPos.x);
        this.node.y = model.startPos.y;
    },

    // 通知碰撞
    setController(controller) {
        this.controller = controller;
    },

    // 碰撞发生
    onCollisionEnter(other, self) {
        if (other.tag === g.CollisionTag.plane || other.tag === g.CollisionTag.planeWing) {
            this.controller.collisionEnemyWithPlane(this.model, this.node.x, this.node.y, other.tag);
        } else if (other.tag === g.CollisionTag.bullet) {
            this.controller.enemyAttacked(this.model, this.node.x, this.node.y);
        }
        cc.log(`other = ${other.tag}, self = ${self.tag}`);
    },

    // 防止超出屏幕
    checkPosX(x) {
        const w = Math.ceil(this.node.width/2);
        if (x < w) {
            return w;
        } else if (x > g.SKY_WIDTH - w) {
            return g.SKY_WIDTH - w;
        }
        return x;
    },

    // TODO 选择敌机
    selectPlane(n) {
        cc.log(`choose enemy index = ${n}`);
        this.model.type = n;
    },

    // 移动敌机
    moving() {
        if (this.model.type === g.EnemyType.first) {
            // 下落
            const move = cc.moveBy(g.AnimTime.enemyDown+randEnemySpeed(), cc.v2(0, g.SKY_HEIGHT*-1));
            const cb = cc.callFunc(function (target) {
                // 敌机消失
                target.destroy();
            }, this);
            this.node.runAction(cc.sequence(move, cb));
        }
        // TODO moving other enemy plane
    },

    // 更新视图
    updateView() {
        const allCmd = this.model.cmd;
        if (allCmd.length < 1) {
            return;
        }
        const actions = [];
        let curTime = 0;
        for (const cmd of allCmd) {
            if (cmd.playTime > curTime) {
                const delay = cc.delayTime(cmd.playTime - curTime);
                actions.push(delay);
            }
            if (cmd.action === g.ActionType.toDie) {
                const toDie = cc.callFunc(function (target) {
                    target.destroy();
                }, this.node);
                actions.push(toDie);
            }
            // TODO other enemy action
            // 上次播放动画需要的时候
            curTime = cmd.playTime+cmd.keepTime;
        }
        if(actions.length === 1) {
            this.node.runAction(actions[0]);
        } else {
            this.node.runAction(cc.sequence(...actions));
        }
    }
    // update (dt) {},
});
